package com.chendx.store.order.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.chendx.model.common.dtos.ResponseResult;
import com.chendx.model.common.enums.AppHttpCodeEnum;
import com.chendx.model.order.dto.ReturnOrderDto;
import com.chendx.model.order.pojo.*;
import com.chendx.model.order.vo.ReturnOrderVo;
import com.chendx.model.user.pojo.User;
import com.chendx.store.common.entity.IdWorker;
import com.chendx.store.order.mapper.*;
import com.chendx.store.order.service.ReturnOrderService;
import com.chendx.store.utils.AppThreadLocalUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.Date;

/**
 * Created by chendx on 2022/4/21.
 */
@Service
@Transactional
public class ReturnOrderServiceImpl extends ServiceImpl<ReturnOrderMapper,ReturnOrder> implements ReturnOrderService {

    @Autowired
    private ReturnCauseMapper returnCauseMapper;
    @Autowired
    private ReturnOrderItemMapper returnOrderItemMapper;
    @Autowired
    private IdWorker idWorker;
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private OrderItemMapper orderItemMapper;
    @Override
    public ResponseResult returnOrder(ReturnOrderDto dto) {
        User user = AppThreadLocalUtils.get();
        if (user == null || user.getId() == null || user.getUsername() == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        String username = user.getUsername();
        if (dto == null || StringUtils.isEmpty(dto.getType())
                || StringUtils.isEmpty(dto.getReturnCauseId()) || StringUtils.isEmpty(dto.getReturnMoney())){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        Order order = orderMapper.selectById(dto.getOrderId());
        OrderItem orderItem = orderItemMapper.selectById(dto.getOrderItemId());
        if (order == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.ORDER_NOT_EXIST);
        }
        if (!order.getPayStatus().equals("1")){
            return ResponseResult.errorResult(AppHttpCodeEnum.ORDER_NOT_PAY);
        }
        if (orderItem == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.ORDER_NOT_EXIST);
        }
        if (orderItem.getIsReturn().equals("3") || orderItem.getIsReturn().equals("1")){
            return ResponseResult.errorResult(AppHttpCodeEnum.RETURNED);
        }
        if (orderItem.getIsReturn().equals("1") || orderItem.getIsReturn().equals("2")){
            return ResponseResult.errorResult(AppHttpCodeEnum.RETURNING);
        }
        //保存退款订单信息
        String returnOrderId = saveReturnOrder(dto, order,username);

        //保存退款订单明细
        Boolean flag = saveReturnOrderItem(dto, returnOrderId);
        if (flag){
            order.setIsReturn(dto.getType());
            orderMapper.updateById(order);
            orderItem.setReturnStatus(dto.getType());
            orderItem.setReturnOrderId(returnOrderId);
            orderItemMapper.updateById(orderItem);
        }
        return ResponseResult.okResult(returnOrderId);
    }

    @Override
    public ResponseResult returnDetail(String id) {
        User user = AppThreadLocalUtils.get();
        if (user == null || user.getId() == null || user.getUsername() == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        String username = user.getUsername();
        if (StringUtils.isEmpty(id)){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        ReturnOrder returnOrder = getById(id);
        ReturnCause returnCause = returnCauseMapper.selectById(returnOrder.getReturnCauseId());
        ReturnOrderVo returnOrderVo = new ReturnOrderVo();
        BeanUtils.copyProperties(returnOrder,returnOrderVo);
        returnOrderVo.setOrderId(String.valueOf(returnOrder.getOrderId()));
        returnOrderVo.setReturnCause(returnCause.getCause());
        returnOrderVo.setReturnOrderId(String.valueOf(returnOrder.getId()));
        return ResponseResult.okResult(returnOrderVo);
    }

    @Override
    public ResponseResult close(ReturnOrderDto dto) {
        User user = AppThreadLocalUtils.get();
        if (user == null || user.getId() == null || user.getUsername() == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        String username = user.getUsername();
        if (dto == null || StringUtils.isEmpty(dto.getReturnOrderId())){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        ReturnOrder returnOrder = getById(dto.getReturnOrderId());
        if (returnOrder == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        if (!returnOrder.getStatus().equals("0")){
            return ResponseResult.errorResult(AppHttpCodeEnum.RETURN_ORDER_IS_DISPOSE);
        }
        Order order = orderMapper.selectById(returnOrder.getOrderId());
        if (order == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.ORDER_NOT_EXIST);
        }
        returnOrder.setStatus("3");
        updateById(returnOrder);
        ReturnOrderItem returnOrderItem =
                returnOrderItemMapper.selectOne(Wrappers.<ReturnOrderItem>lambdaQuery().eq(ReturnOrderItem::getReturnOrderId, dto.getReturnOrderId()));
        OrderItem orderItem = orderItemMapper.selectById(returnOrderItem.getOrderItemId());
        orderItem.setReturnStatus("0");
        orderItem.setReturnOrderId(null);
        orderItemMapper.updateById(orderItem);
        Integer count = orderItemMapper.selectCount(Wrappers.<OrderItem>lambdaQuery().eq(OrderItem::getOrderId, order.getId()).ne(OrderItem::getReturnStatus, "0"));
        if (count == 0){
            order.setIsReturn("0");
            orderMapper.updateById(order);
        }
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }


    public String saveReturnOrder(ReturnOrderDto dto,Order order,String username){
        ReturnOrder returnOrder = new ReturnOrder();
        String returnOrderId = idWorker.nextId()+"";
        returnOrder.setId(Long.valueOf(returnOrderId));
        returnOrder.setOrderId(Long.valueOf(dto.getOrderId()));
        returnOrder.setApplyTime(new Date());
        returnOrder.setUserId((long) 2);
        returnOrder.setUserAccount(username);
        returnOrder.setLinkman(order.getReceiverContact());
        returnOrder.setLinkmanMobile(order.getReceiverMobile());
        returnOrder.setIsReturnFreight(dto.getIsReturnFeight());
        returnOrder.setReturnCauseId(dto.getReturnCauseId());
        returnOrder.setEvidence(dto.getEvidence());
        returnOrder.setDescription(dto.getDescription());
        returnOrder.setType(dto.getType());
        returnOrder.setStatus("0");
        returnOrder.setReturnMoney(dto.getReturnMoney());
        save(returnOrder);
        return returnOrderId;
    }

    public Boolean saveReturnOrderItem(ReturnOrderDto dto,String returnOrderId){
        try {
            ReturnOrderItem returnOrderItem = new ReturnOrderItem();
            BeanUtils.copyProperties(dto,returnOrderItem);
            returnOrderItem.setTitle(dto.getName());
            returnOrderItem.setCategoryId(Long.valueOf(dto.getCategoryId3()));
            returnOrderItem.setReturnOrderId(Long.valueOf(returnOrderId));
            returnOrderItem.setOrderId(Long.valueOf(dto.getOrderId()));
            returnOrderItem.setOrderItemId(Long.valueOf(dto.getOrderItemId()));
            returnOrderItemMapper.insert(returnOrderItem);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }
}
